package study.optional.序列化问题;

import study.optional.公共类.Car;
import study.optional.公共类.Insurance;

import javax.swing.text.html.Option;
import java.util.Optional;
import java.util.function.Function;

/**
 * @Author 刘伟涛
 * @Date 2023/6/30 15:08
 **/
public class Demo01 {
    public static void main(String[] args) {
        User user = new User(new Car(Optional.ofNullable(new Insurance("张三"))));
        Function<User,String> nameApply = u -> Optional.ofNullable(u)
                .flatMap(User::getOptCar)
                .flatMap(Car::getInsurance)
                .map(Insurance::getName)
                .orElse("这是空的");
        System.out.println(nameApply.apply(user));

        /*空值测试*/
        User user1 = null;
        Optional<Car> car = Optional.ofNullable(user1).flatMap(User::getOptCar);
        System.out.println(car);
        System.out.println(Optional.empty());
        System.out.println(nameApply.apply(user1));
    }
}

/**
 * 使用下面方式避免Optional的序列化问题
 */
class User{
    Car car;
    User(){

    }
    User(Car car){
        this.car = car;
    }
    public Optional<Car> getOptCar(){
        return Optional.ofNullable(car);
    }
}
